#import "NetWorkManager.h"
#import <SystemConfiguration/SCNetworkReachability.h>
#import "PopUIManager.h"
#import "UserInfo.h"

//static const NSString * SERVER_URL = @"http://server.ibaobeimao.com/main.php?action=bbmserver";
@implementation NetWorkManager

static NetWorkManager* netWorkMgr;

+(NetWorkManager*)getInstanse{
    if (netWorkMgr == nil) {
        netWorkMgr = [[NetWorkManager alloc]init];
    }
    return netWorkMgr;
}


/**
 判断是否有网络连接
 */
+ (BOOL)connectedToNetwork
{
    //创建零地址，0.0.0.0的地址表示查询本机的网络连接状态
    struct sockaddr_storage zeroAddress;//IP地址
    
    bzero(&zeroAddress, sizeof(zeroAddress));//将地址转换为0.0.0.0
    zeroAddress.ss_len = sizeof(zeroAddress);//地址长度
    zeroAddress.ss_family = AF_INET;//地址类型为UDP, TCP, etc.
    
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    //获得连接的标志
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    //如果不能获取连接标志，则不能连接网络，直接返回
    if (!didRetrieveFlags)
    {
        return NO;
    }
    //根据获得的连接标志进行判断
    
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    BOOL isConnected = (isReachable&&!needsConnection) ? YES : NO;
    NSLog(@"NET STAT: %d",isConnected);
    return isConnected;
}

//(void)post:(NSString *)URL RequestParams:(NSDictionary *)params FinishBlock:(void (^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block
//异步请求网络
-(BOOL)requestURLAsynMessage:(NSString*)message data:(NSString*)jsonData FinishBlock:(void(^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block
{
    NSString *str = [NSString stringWithFormat:@"%@&message=%@&data=%@",SERVER_URL,message,jsonData];
    NSLog(@"请求的地址URL:  %@",str);
    NSString * str_url = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 1.创建请求
   NSURL *url = [NSURL URLWithString:str_url];
   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
   
   // 2.设置缓存策略(有缓存就用缓存，没有缓存就重新请求)
    request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
    request.timeoutInterval = 8;
    // 3.发送请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:block];
    return true;
}

//同步请求服务器
-(NSDictionary*)requestURLSynMessage:(NSString*)message data:(NSString*)jsonData{
    NSString *str = [NSString stringWithFormat:@"%@&message=%@&data=%@",SERVER_URL,message,jsonData];
    NSLog(@"STR: %@",str);
    NSString * str_url = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //1.设置请求路径
    NSURL *url2=[NSURL URLWithString:str_url];
    NSLog(@"%@",url2);
    //    2.创建请求对象
    NSURLRequest *request2 = [[NSURLRequest alloc]initWithURL:url2 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    
    NSLog(@"timeout: %f",request2.timeoutInterval);
    //    3.发送请求
    //发送同步请求，在主线程执行
    NSData *data=[NSURLConnection sendSynchronousRequest:request2 returningResponse:nil error:nil];
    //（一直在等待服务器返回数据，这行代码会卡住，如果服务器没有返回数据，那么在主线程UI会卡住不能继续执行操作）
    
    NSDictionary *dict = nil;
    if (data != nil) {
        NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"NET RECEIVE: %@",responseString);
        
        dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",dict);
    }
    return dict;
}

//上传单张图片到服务器，用于修改用户的图像等功能。
-(BOOL)uploadImageToServer:(UIImage*)img FinishBlock:(void(^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block{
    NSData *imgData = UIImageJPEGRepresentation(img, 0.3);
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @"2", @"utype",@"0", @"uid",@"USER_POST_AVATAR", @"message",nil];

    NSString *TWITTERFON_FORM_BOUNDARY = @"0xKhTmLbOuNdArY";
    //根据url初始化request
    NSMutableURLRequest* request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:SERVER_URL]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 --AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];

    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    for (NSString* temp_key in dict) {
        //添加分界线，换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //添加字段名称，换2行
        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",temp_key];
        //添加字段的值
        [body appendFormat:@"%@\r\n",[dict objectForKey:temp_key]];
        
        NSLog(@"添加字段的值==%@",[dict objectForKey:temp_key]);
    }
    
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[[NSDate  date] timeIntervalSince1970]];
    float rd = ((arc4random()%100000) + 1) * 1.0 / 100000;
    NSString *image_name_str = [NSString stringWithFormat:@"pic%@%f.jpg",timeSp,rd];
    NSLog(@"image Name >> %@",image_name_str);
    
    //声明pic字段，文件名为pic0.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic0\"; filename=\"%@\"\r\n",image_name_str];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg\r\n\r\n"];
    
    //声明结束符：--AaB03x--
    NSString *end2=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];

    //将image的data加入
    [myRequestData appendData:imgData];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end2 dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request2 setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request2 setValue:[NSString stringWithFormat:@"%ld", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request2 setHTTPBody:myRequestData];
    //http method
    [request2 setHTTPMethod:@"POST"];
    
    [NSURLConnection sendAsynchronousRequest:request2 queue:[NSOperationQueue mainQueue] completionHandler:block];

    return YES;

}

//多图片上传时，一定要压缩图片的大小，图片过大的时候无法上传图片
//上传多张图片到服务器，用于发布通知，发布照片。
-(BOOL)uploadMultipleImageToServer:(NSMutableDictionary*)dict_info imageArray:(NSMutableArray*) imageArrays FinishBlock:(void(^)(NSURLResponse *response, NSData *data, NSError *connectionError)) block{

    NSString *TWITTERFON_FORM_BOUNDARY = @"0xKhTmLbOuNdArY";
    //根据url初始化request
    NSMutableURLRequest* request2 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:SERVER_URL]
                                                            cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                        timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary = [[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 --AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    for (NSString* temp_key in dict_info) {
        //添加分界线，换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //添加字段名称，换2行
        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",temp_key];
        //添加字段的值
        [body appendFormat:@"%@\r\n",[dict_info objectForKey:temp_key]];
    }
    
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    
    int index = 0;
    for (UIImage* img in imageArrays) {
        NSMutableString *body_format = [[NSMutableString alloc]init];
        [body_format appendFormat:@"%@\r\n",MPboundary];
        
        NSData *imgData = UIImageJPEGRepresentation(img, 0.1);
        //创建待上传到服务器的图片名称
        NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
        float rd = ((arc4random()%100000) + 1) * 1.0 / 100000;
        NSString *image_name_str = [NSString stringWithFormat:@"pic%@%f.jpg",timeSp,rd];
//      NSLog(@"image Name >> %@",image_name_str);
        
        //声明pic字段，文件名为pic0.png
        [body_format appendFormat:@"Content-Disposition: form-data; name=\"pic%d\"; filename=\"%@\"\r\n",index, image_name_str];
        index++;
        //声明上传文件的格式
        [body_format appendFormat:@"Content-Type: application/octet-stream; charset=utf-8\r\n\r\n"];
        
        [myRequestData appendData:[body_format dataUsingEncoding:NSUTF8StringEncoding]];
        //将image的data加入
        [myRequestData appendData:imgData];
        [myRequestData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    //声明结束符：--AaB03x--
    NSString *end2=[[NSString alloc]initWithFormat:@"%@\r\n",endMPboundary];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end2 dataUsingEncoding:NSUTF8StringEncoding]];
     NSLog(@"%@",end2);
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request2 setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request2 setValue:[NSString stringWithFormat:@"%ld", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request2 setHTTPBody:myRequestData];
    //http method
    [request2 setHTTPMethod:@"POST"];
    
    [NSURLConnection sendAsynchronousRequest:request2 queue:[NSOperationQueue mainQueue] completionHandler:block];
    return YES;
    
}

@end
